$(document).ready(function () {
    // Draw pics
    $.getJSON('/b2dsc/handle_ajax', {
        jid: $('#job-id').text(), category: 'done',
        // 因为这里是页面加载时就运行的，所以调取 pI, qC 没问题。
        keys: 'pIdent qCover max_cnts chromosome_length'
    }, function (done) {
        var dp_sid = $('#sid').val();
        var pIqC = done.pIdent + '_' + done.qCover;
        var max_v = done.max_cnts[pIqC][dp_sid];
        $('#max_cnt').text(max_v);
        var lower_upper = get_lower_upper_limits();
        var vl = lower_upper[0], vu = lower_upper[1];
        $('#lower-limit').attr('max', max_v);
        $('#upper-limit').attr('max', max_v);
        if (vu > max_v) {
            $('#upper-limit').val(max_v);
            vu = max_v;
        }
        reset_steps(vl, vu);

        // 染色体长度
        var maxCLen = 0;
        $.each(done.chromosome_length, function (gn, cLens) {
            $.each(cLens, function (idx, len) {
                maxCLen = (len > maxCLen) ? len : maxCLen;
            });
        });
        if (maxCLen / 1e6 < 100) {
            $('#px-per-Mbp').val(10);
        }
    });

    $('#lower-limit').change(function () {
        var lower_upper = get_lower_upper_limits();
        var vl = lower_upper[0], vu = lower_upper[1];
        var max = parseInt($(this).attr('max'));

        if (vl > max) {
            vl = max; vu = max;
        } else if (vl > vu) {
            vl = vu;
        }
        if (vl < 0) vl = 0;
        reset_lower_upper(vl, vu);
        reset_steps(vl, vu);
    });
    $('#upper-limit').change(function () {
        var lower_upper = get_lower_upper_limits();
        var vl = lower_upper[0], vu = lower_upper[1];
        var max = parseInt($(this).attr('max'));
        if (vu < vl) vu = vl;
        if (vu > max) vu = max;
        reset_lower_upper(vl, vu);
        reset_steps(vl, vu);
    });

    function reset_lower_upper(vl, vu) {
        $('#lower-limit').val(vl);
        $('#upper-limit').val(vu);
        $('#v-lower-limit').html(vl);
        $('#v-upper-limit').html(vu);
    }

    function get_lower_upper_limits() {
        return [
            parseInt($('#lower-limit').val()) || 0,
            parseInt($('#upper-limit').val()) || 100
        ];
    }

    function reset_steps(vl, vu) {
        if (vu - vl < 100) {
            $('#steps').val(vu - vl);
        } else {
            $('#steps').val(100);
        }
        check_low_up_colors4steps();
    }

    // SVG
    $('.size-param').hide();
    $('.offset-param').hide();
    $('#size-params').click(function (event) {
        event.preventDefault();
        $('.size-param').toggle();
    });
    $('#offset-params').click(function (event) {
        event.preventDefault();
        $('.offset-param').toggle();
    });
    $('#color-params').click(function (event) {
        event.preventDefault();
        $('.color-param').toggle();
    });

    // 图片
    // 及时变换上下限， steps
    $('#sid').change(function () {
        var v1 = $(this).val();
        var justPlotted = $('#sid-just-plotted').html();
        if (justPlotted != v1) {
            $('#pic-countsPerM').hide();
        } else {
            $('#pic-countsPerM').show();
        }
        $.getJSON('/b2dsc/handle_ajax', {
            jid: $('#job-id').text(), category: 'done',
            // keys: 'pIdent qCover max_cnts'
            // 不可从 done.json 里直接调取 pI, qC
            keys: 'max_cnts'
        }, function (done) {
            // done.pIdent = +$('#current-pI').text(), done.qCover = +$('#current-qC').text();
            // var pIqC = done.pIdent + '_' + done.qCover;
            // 比如 +'100.00' == 100，将会出现问题。
            var pIqC = $('#current-pI').text() + '_' + $('#current-qC').text();
            var max_cnts = done.max_cnts[pIqC];
            $('#lower-limit').attr('max', max_cnts[v1]);
            $('#upper-limit').attr('max', max_cnts[v1]);
            $('#max_cnt').text(max_cnts[v1]);
            var vL = 0, vu = 100;
            if (vu > max_cnts[v1]) {
                vu = max_cnts[v1];
                $('#upper-limit').val(vu);
            }
            $('#lower-limit').val(vL);
            $('#upper-limit').val(vu);
            $('#v-lower-limit').html(vL);
            $('#v-upper-limit').html(vu);
            reset_steps(vL, vu);
        });
    });
    // 颜色设定变化时
    $('#lower-limit-color').change(function () {
        check_low_up_colors4steps();
    });
    $('#upper-limit-color').change(function () {
        check_low_up_colors4steps();
    });

    function check_low_up_colors4steps() {
        var lcol = $('#lower-limit-color').val();
        var ucol = $('#upper-limit-color').val();
        if (lcol === ucol) {
            $('#steps').val(0);
        }
    }

    // 在新页面打开 SVG
    $('#save-countsPerM-svg').click(function () {
        var sid = $('#sid').val();
        var svgxml = $('#svg-countsPerM').html();
        svgxml = '<?xml version="1.0" encoding="UTF-8" ?>' + "\n" + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' + svgxml;
        var blob = new Blob([svgxml], { type: 'image/svg+xml;charset=utf-8' });
        saveAs(blob, sid + ".svg");
    });

    // offset
    $('input.em-unit').attr('title', '1em equals the current font size.');
    $('input.tick-mark2label').attr('title', 'Space width, from tick mark to tick label');

    var black = 'rgb(0, 0, 0)', white = 'rgb(255, 255, 255)',
        darkblue = 'rgb(0, 0, 139)', blue = 'rgb(0, 0, 255)',
        red = 'rgb(255, 0, 0)';
    $('#black-theme').click(function (event) {
        event.preventDefault();
        blackTheme();
    });
    $('#white-theme').click(function (event) {
        event.preventDefault();
        whiteTheme();
    });

    function setColor(id, color) {
        $('#' + id).val(color);
        $('#' + id).spectrum({
            color: color,
            preferredFormat: "rgb",
            showInput: true,
            showPalette: true,
            palette: [
                ['black', 'white', 'blue'],
                ['red', 'rgb(0, 255, 0)', 'rgb(190, 190, 190)'],
                ['darkblue']
            ],
            maxSelectionSize: 3
        });
    }

    function blackTheme() {
        setColor('bg-color', black);
        setColor('fg-color', white);
        setColor('chr-fill', darkblue);
        setColor('chr-stroke', darkblue);
        setColor('lower-limit-color', blue);
        setColor('upper-limit-color', red);
    }

    function whiteTheme() {
        setColor('bg-color', white);
        setColor('fg-color', black);
        setColor('chr-fill', white);
        setColor('chr-stroke', black);
        setColor('lower-limit-color', white);
        setColor('upper-limit-color', red);
    }

    whiteTheme();
});